#!/bin/sh -
# -*- coding: utf-8 -*-

import SimpleHTTPServer
import BaseHTTPServer
import urlparse
import cgi
import pprint
import json
import urllib

class ServerRequestHandler(SimpleHTTPServer.SimpleHTTPRequestHandler):
    def do_POST1(self):
        parsed_path = urlparse.urlparse(self.path)
        postdata = self.rfile.read(1024)
        message = '<br>'.join([
                'CLIENT VALUES:',
                'client_address=%s (%s)' % (self.client_address,
                                            self.address_string()),
                'command=%s' % self.command,
                'path=%s' % self.path,
                'real path=%s' % parsed_path.path,
                'query=%s' % parsed_path.query,
                'request_version=%s' % self.request_version,
                'data=%s' % postdata,
                '',
                'SERVER VALUES:',
                'server_version=%s' % self.server_version,
                'sys_version=%s' % self.sys_version,
                'protocol_version=%s' % self.protocol_version,
                '',
                ]) 
        self.send_response(200)
        self.end_headers()
        self.wfile.write(message)
        return
    def do_POST2(self):
#        global rootnode
#        try:
            ctype, pdict = cgi.parse_header(self.headers.getheader('content-type'))
            print ctype
            if ctype == 'multipart/form-data':
                self.body = cgi.parse_multipart(self.rfile, pdict)
            elif ctype == 'application/x-www-form-urlencoded':
                qs = self.rfile.read(1024)
                self.body = cgi.parse_qs(qs, keep_blank_values=1)
            else:
                self.body = ''                   # Unknown content-type
            self.send_response(301)
            
            self.end_headers()

            print "filecontent",self.body 
            self.wfile.write("<HTML>POST OK.<BR><BR>")
            self.wfile.write(self.body)            
#        except :
#            print 'err'
    def do_POST(self):
        print self.path
        outfile='lala'
        if(self.path=='/hides.json'):
            outfile='hides.json'
        elif(self.path=='/regs.txt'):
            outfile='regs.txt'
        elif(self.path=='/adblock.user.txt'):
            outfile='adblock.user.txt'
        len, pdict = cgi.parse_header(self.headers.getheader('Content-Length'))
        #print len
        s=str(self.rfile.read(int(len)))
        #print s #(urllib.parse.parse_qs(urllib.parse.unquote(s))) 
        fo = open(outfile,'wb')
        fo.write(s)
        fo.close
        self.send_response(200)
        self.end_headers()
        self.wfile.write(s)     
    def do_GET(self):
        print self.path
        #pprint.pprint(self.headers.get('referer','.'))
        if(self.path=='/adblockie'):
            self.send_response(200)
            self.send_header("Cache-Control", 'no-cache')
            self.end_headers()
            #s=readfile('jquery.js')+'\n'
            #s+=readfile('dump.js')+'\n'
            #s+=readfile('hides.js')+'\n'
            #s+=readfile('adblockie.js')+'\n'
            #print s
            s = ''
            self.wfile.write(s) 
        elif(self.path.find('/adblockie.css')==0):
            self.send_response(200)
            self.send_header("Cache-Control", 'no-cache')
            self.end_headers()
            s=getcss(self.headers.get('referer','.'))
            #print s
            #print s
            #print self.headers
            self.wfile.write(s)
        elif(self.path.find('/updatelist')==0):
            self.send_response(200)
            self.send_header("Cache-Control", 'no-cache')
            self.end_headers()
            webfile = urllib.urlopen("http://adblock-chinalist.googlecode.com/svn/trunk/adblock.txt").read()
            fp = file('adblock.txt', 'w')
            fp.write(webfile)
            fp.close()
            self.wfile.write(webfile) 
        elif(self.path.find('/ajaxget/')==0):
            self.send_response(200)
            self.send_header("Cache-Control", 'no-cache')
            self.end_headers()
            url = self.path[9:]
            #print url
            webfile = urllib.urlopen(url).read()
            self.wfile.write(webfile)
        else:
            f = self.send_head()
            if f:
                self.copyfile(f, self.wfile)
                f.close()
def test(HandlerClass = ServerRequestHandler,
         ServerClass = BaseHTTPServer.HTTPServer, 
         protocol="HTTP/1.0",
         port=8001):
    """Test the HTTP request handler class.

    This runs an HTTP server on port 8000 (or the first command line
    argument).

    """

    server_address = ('', port)

    HandlerClass.protocol_version = protocol
    httpd = ServerClass(server_address, HandlerClass)

    sa = httpd.socket.getsockname()
    print "Serving HTTP on", sa[0], "port", sa[1], "..."
    httpd.serve_forever()
def readfile(file):
    f = open(file)
    s = f.read()
    f.close
    return s
def getcss(ref):
    css = ''
    hides = json.loads(readfile('hides.json'))
    for hide in hides:
        if(hide['selectorDomain']==None):
            #print hide
            css += hide['selector']+'{display:none;}\n'
        else:
            domes = hide['selectorDomain'].split(',')
            for d in domes:
                if(ref.find(d)>=0):
                    #print hide
                    css += hide['selector']+'{display:none;}\n'
                    break
    return css
if __name__ == '__main__':
    print getcss('sina.com.cn')